$.cookie("setpageurl",location.href);
var id;
if($.cookie("MYID")){id=$.cookie("MYID")};
var returnurl=encodeURIComponent("http://www.pulu.com/weixin/setpage1.html"); //同意后跳转页面
//最新动态列表页
$("#lastinfopage").click(function(){
    $.cookie("otherid","");
    location.href="lastinfo.html";
});
//别人回复提醒 详情页
$("#answernotic div").click(function(){
    $.cookie("noticdelid","firstin");
    location.href="mynotic.html";
});
//拒绝提醒框关闭
$("#ikonw2").click(function(){
    $("#friendInfor2").css("display","none");
});
//所有方法
function allftn(){
    <!--模态框淡入淡出-->
    var overflowlist=document.getElementsByClassName("overflow");
    var modalbg=document.getElementsByClassName("modal_bg")[0];
    var modal=document.getElementsByClassName("action_menu_container")[0];
    var cancel=document.getElementById("cancel");
    var timer;
    for(var i=0;i<overflowlist.length;i++){
        overflowlist[i].onclick=function(){
            modalbg.style.display="block";
            modal.style.display="block";
        }
    };
    cancel.onclick=function(){
        if(modalbg.style.display=="block"&&modal.style.display=="block"){
            modalbg.className+=' animate_out';
            modal.className+=' animate_out';
        }
        timer=setTimeout(changeclass,100);
    };
    function changeclass(){
        modalbg.className='modal_bg';
        modal.className='action_menu_container';
        clearTimeout();
        timer=null;
        changedisplay();
    };
    function changedisplay(){
        modalbg.style.display="none";
        modal.style.display="none";
    };
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    var id= $.cookie("MYID");
//编辑资料 页面跳转
    document.getElementById("bjzl").onclick=function(){
        location.href="mysetpage.html";
    };
//屏蔽管理 页面跳转
    $("#pbgl").click(function(){
        location.href="shieldpage.html";
    });
//个人账户
    document.getElementById("myscore").onclick=function(){
        location.href="scoredetial.html";
    };
//我的问题 页面跳转
    $("#myaskbtn").click(function(){
        location.href="myquestionlist.html";
    });
//我的回答 页面跳转
    $("#myanswerbtn").click(function(){
        location.href="myquestionlist2.html";
    });
//我的经验 页面跳转
    $("#myexpbtn").click(function(){
        location.href="myquestionlist1.html";
    });
//我的收藏 页面跳转
    $("#mycollectbtn").click(function(){
        location.href="myquestionlist5.html";
    });
//退出登录
    $("#signout").click(function(){
        $.ajax({
            type:"post",
            url:opendeluser,
            data:{"openId":$.cookie("wxopenid")},
            success:function(d){
                id="";
                $.cookie("MYID","");
                location.href="login.html";
            }
        });
    });
//点击展开大图
//    $(".photo").click(function(){
//        if(haveimg=="yes"){
//            var imgheight=$("#showimg").height();
//            var bigheight=window.screen.availHeight;
//            $("#digimgplace").height(bigheight);
//            if(bigheight>imgheight){
//                $("#showimg").css("marginTop",(bigheight-imgheight)/2);
//            }
//            $("#digimgplace").css("display","block");
//            $("#page_wrapper").css("display","none");
//        }
//    });
//关闭大图
    $("#digimgplace").click(function(){
        $("#digimgplace").css("display","none");
        $("#page_wrapper").css("display","block");
    });
//加载中定位
    var wh=window.screen.availHeight;
    var marginheight=(wh-80)/2;
    //$("#waitplace>div").css("marginTop",marginheight+"px");
    //$("body").css("height",wh+"px");
    $("#page_wrapper").css("height",wh-130+"px");
    $("#page_wrapper").css("overflow","hidden");
    // console.log(document.getElementsByTagName("body")[0].style.height);

    $().ready(function(){
        //获取回复动态
        $.ajax({
            type:"get",
            url:getanswernumurl+id,
            datatype:"json",
            success:function(d){
                //console.log("回答动态",d);
                if(d.Data>0){
                    $("#answernotic div span").html(d.Data);
                    $("#answernotic").css("display","block");
                    $("#newnotenotice").css("display","block");
                    $("#newnotenotice").html(d.Data);
                }else{
                    $("#answernotic").css("display","none");
                }
            }
        });
        //加载页面
        $.ajax({
            type: "post",
            //提交的网址
            url: "http://42.62.66.198:9001/api/puluuser/getuser",
            //提交的数据
            data: { "userId": id },
            //返回数据的格式
            datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".

            //成功返回之后调用的函数
            success: function (data) {
                //等待区域隐藏
                $("#waitplace").css("display","none");
                $("#page_wrapper").css("height","auto");
                $("#page_wrapper").css("overflow","auto");

                //console.log(data.Data);
                $("#page_title").html(data.Data.nick);
                $("#nickname").html(data.Data.nick);
                if(data.Data.userAva){
                    haveimg="yes";
                    //$(".photo").append("<img class='profile_photo_img' src='http://42.62.66.198:8003/"+data.Data.userAva+"'>");
                    $("#photo img").attr("src","http://42.62.66.198:8003/"+data.Data.userAva);
                    $("#photo img").css("display","block");
                    $("#digimgplace").css("background-image","url('http://42.62.66.198:8003/"+data.Data.userAva+"')");
                }
                if(data.Data.sex===1){
                    document.getElementById("sex1").style.display="inline-block";
                }else if(data.Data.sex===0){
                    document.getElementById("sex2").style.display="inline-block";
                }
                $("#cover").html(data.Data.cover);
                $("#myword").html(data.Data.sign);
                $("#city").html(data.Data.city);
                $("#educationword").html(data.Data.education);
                var jobs="";
                for(var i= 0;i<data.Data.jobs.length;i++){
                    jobs+=data.Data.jobs[i].typename+"&nbsp;&nbsp;"
                }
                $("#myjobs").html(jobs);
                var news="";
                for(var n= 0;n<data.Data.news.length;n++){
                    news+=data.Data.news[n].typename+"&nbsp;&nbsp;"
                }
                $("#mynews").html(news);

                var hobby="";
                for(var r= 0;r<data.Data.hobbys.length;r++){
                    hobby+=data.Data.hobbys[r].typename+"&nbsp;&nbsp;"
                }
                $("#myhobby").html(hobby);
                $("#visitedcity").html(data.Data.visitedcity);
                //铺路信息
                $("#scoreword").html(Math.round(parseFloat(data.Data.score))/100+"元");
                $("#myquestionCount").html(data.Data.myquestionCount+"条");
                $("#myanswerCount").html(data.Data.myanswerCount+"条");
                $("#myexpCount").html(data.Data.myexpCount+"条");
                $("#mycollecttionCount").html(data.Data.mycollecttionCount+"条");
                //陌生人可见
                if(data.Data.statusstrangesee===1){//可见
                    document.getElementById("seemeimg1").style.display="none";
                    document.getElementById("seemeimg2").style.display="block";
                }else if(data.Data.statusstrangesee===0){//不可见
                    document.getElementById("seemeimg1").style.display="block";
                    document.getElementById("seemeimg2").style.display="none";
                }
            }
        });
        //最新动态
        $.ajax({
            type:"get",
            datatype:"json",
            url:"http://42.62.66.198:9001/api/PuluUser/GetUserStatusByUserId?userId="+id+"&currentIndex=1&pageSize=10",
            success:function(data){
                //console.log("最新动态");
                //console.log(data);
                for(var i=0;i<data.Data.length;i++){
                    var des="";
                    if(data.Data[i].des||data.Data[i].answerContent){
                        var word=data.Data[i].des||data.Data[i].answerContent;
                        des="<div class='desword' style='padding-bottom:5px;'>"+word+"</div>";
                    };
                    var score="";
                    if(data.Data[i].score){
                        score="<span class='scoreword'>"+data.Data[i].score+"</span>";
                    }
                    if(data.Data[i].contenttypeName==="经验"){
                        var hrefto1="href=shareexppage.html?eid="+data.Data[i].contentid;
                        //var tim1=data.Data[i].time.match(/([0-9\-]+)/)[0];
                        var tim1=getDateDiff(getDateTimeStamp(data.Data[i].time));
                        if(!tim1){
                            tim1="刚刚";
                        }
                        $("#setpagenewslist").append("<div class='pagedlist_item'> <div class='feed_item feed_type_question'> <div class='EventHeader'> <span>您"+data.Data[i].operatetypeName+"了此"+data.Data[i].contenttypeName+"</span>"+score+"<span class='rt'>"+tim1+"</span> </div>"+des+"<h2 class='no_highlight'> <a class='question_link'"+hrefto1+">"+data.Data[i].content+"</a> </h2> <div class='ContentFooter QuestionFooter'> <span class='answer_count'>浏览</span> <span class='answer_count'>"+data.Data[i].count+"</span> </div> </div> </div>");
                    }else if(data.Data[i].contenttypeName==="问题"){
                        var hrefto2="href=questiondetail.html?qid="+data.Data[i].contentid;
                        //var tim2=data.Data[i].time.match(/([0-9\-]+)/)[0];
                        // <div class='ContentFooter QuestionFooter'> <span class='answer_count'>回答</span> <span class='answer_count'>"+data.Data[i].count+"</span> </div>
                        var tim2=getDateDiff(getDateTimeStamp(data.Data[i].time));
                        if(!tim2){
                            tim2="刚刚";
                        }
                        $("#setpagenewslist").append("<div class='pagedlist_item'> <div class='feed_item feed_type_question'> <div class='EventHeader'> <span>您"+data.Data[i].operatetypeName+"了此"+data.Data[i].contenttypeName+"</span>"+score+"<span class='rt'>"+tim2+"</span> </div>"+des+"<h2 class='no_highlight'> <a class='question_link'"+hrefto2+">"+data.Data[i].content+"</a> </h2> </div> </div>");
                    }else if(data.Data[i].contenttypeName==="新闻"){
                        var hrefto3="href="+data.Data[i].url;
                        //var tim3=data.Data[i].time.match(/([0-9\-]+)/)[0];
                        var tim3=getDateDiff(getDateTimeStamp(data.Data[i].time));
                        if(!tim3){
                            tim3="刚刚";
                        }
                        $("#setpagenewslist").append("<div class='pagedlist_item'> <div class='feed_item feed_type_question'> <div class='EventHeader'> <span>您"+data.Data[i].operatetypeName+"了此"+data.Data[i].contenttypeName+"</span> <span class='rt'>"+tim3+"</span> </div>"+des+"<h2 class='no_highlight'> <a class='question_link'"+hrefto3+">"+data.Data[i].content+"</a> </h2> <div class='ContentFooter QuestionFooter'> <span class='answer_count'>浏览</span> <span class='answer_count'>"+data.Data[i].count+"</span> </div> </div> </div>");
                    }
                }
            }
        });
        //陌生人查看十条
        $("#seeme").click(function(){
            if(document.getElementById("seemeimg1").style.display==="block"){
                document.getElementById("seemeimg1").style.display="none";
                document.getElementById("seemeimg2").style.display="block";
                $.ajax({
                    type:"post",
                    datatype:"json",
                    url:"http://42.62.66.198:9001/api/PuluUser/OpenStrangerSee",
                    data:{"userId":id},
                    success:function(d){
                        //console.log("陌生人看十条");
                        //console.log(d);
                    }
                })
            }else if(document.getElementById("seemeimg2").style.display==="block"){
                document.getElementById("seemeimg1").style.display="block";
                document.getElementById("seemeimg2").style.display="none";
                $.ajax({
                    type:"post",
                    datatype:"json",
                    url:"http://42.62.66.198:9001/api/PuluUser/CloseStrangerSee",
                    data:{"userId":id},
                    success:function(d){
                        //console.log("解除陌生人看十条");
                        //console.log(d);
                    }
                })
            }
        });
    });
//环信建立连接
    var conn = new WebIM.connection({
        https: WebIM.config.https,
        url: WebIM.config.xmppURL,
        isAutoLogin: WebIM.config.isAutoLogin,
        isMultiLoginSessions: WebIM.config.isMultiLoginSessions
    });
//登录
    var options = {
        apiUrl: WebIM.config.apiURL,
        user:id,
        pwd:id,
        appKey: "pulu#pulu"
    };
    conn.open(options);

    var handlePresence = function ( e ) {
        //（发送者希望订阅接收者的出席信息），即别人申请加你为好友
        if ( e.type === 'subscribe' ) {
            console.log("别人加你好友2");
            $.ajax({
                type:"post",
                datatype:"json",
                url:"http://42.62.66.198:9001/api/puluuser/getuser",
                data:{"userId": e.from},
                success:function(fd){
                    //console.log("好友申请："+fd.Data.nick);
                    var infor=fd.Data.nick+"&nbsp;"+"："+ e.status;
                    $("#fromwho").html(infor);
                    $("#friendInfor").css("display","block");
                    //同意添加好友
                    $("#iamagree").click(function(){
                        conn.subscribed({
                            to: e.from,
                            message : "[resp:true]"
                        });
                        //conn.subscribe({//需要反向添加对方好友
                        //    to: e.from,
                        //    message : "[resp:true]"
                        //});
                        //关闭提示框
                        $("#friendInfor").css("display","none");
                        $.ajax({
                            type:"post",
                            datatype:"json",
                            url:"http://42.62.66.198:9001/api/PuluGoodFriend/Addpulu_goodfriend",
                            data:{"userId":e.from,"friendId":id},
                            success:function(d){
                                //console.log("好友数据以保存");
                                //console.log(d);
                            }
                        })
                    });
                    //拒绝添加好友
                    $("#iampass").click(function(){
                        conn.unsubscribed({
                            to: e.from,
                            message : "拒绝"
                        });
                        $("#friendInfor").css("display","none");
                    })
                }
            });
            //console.log(e);
            //若e.status中含有[resp:true],则表示为对方同意好友后反向添加自己为好友的消息，demo中发现此类消息，默认同意操作，完成双方互为好友；如果不含有[resp:true]，则表示为正常的对方请求添加自己为好友的申请消息。
        }
        //(发送者允许接收者接收他们的出席信息)，即别人同意你加他为好友
        if ( e.type === 'subscribed' ) {
            //console.log("别人同意了你的好友请求");
            //console.log(e);
            $.ajax({
                type:"post",
                datatype:"json",
                url:"http://42.62.66.198:9001/api/puluuser/getuser",
                data:{"userId": e.from},
                success:function(d){
                    var infor=fd.Data.nick+"&nbsp;"+"同意了您的好友请求";
                    $("#iamagree2").html(infor);
                    $("#friendInfor2").css("display","block");
                    $("#iknow2").click(function(){
                        $("#friendInfor2").css("display","none");
                    })
                }
            });
        }
        //（发送者取消订阅另一个实体的出席信息）,即删除现有好友
        if ( e.type === 'unsubscribe' ) {
            //console.log("删除好友");
            //console.log(e);
        }
        //（订阅者的请求被拒绝或以前的订阅被取消），即对方单向的删除了好友
        if ( e.type === 'unsubscribed' ) {
            //console.log("你的好友请求被拒绝");
            //console.log(e);
            $.ajax({
                type:"post",
                datatype:"json",
                url:"http://42.62.66.198:9001/api/puluuser/getuser",
                data:{"userId": e.from},
                success:function(d){
                    var infor=fd.Data.nick+"&nbsp;"+"拒绝了您的好友请求";
                    $("#iamagree2").html(infor);
                    $("#friendInfor2").css("display","block");
                    $("#iknow2").click(function(){
                        $("#friendInfor2").css("display","none");
                    })
                }
            });
        }
    };
    conn.listen({
        onPresence: function ( message ) {
            handlePresence(message);
        },//收到联系人订阅请求、处理群组、聊天室被踢解散等消息
        onOpened: function ( message ) {          //连接成功回调
            //如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
            conn.setPresence();
            //console.log("与环信连接成功");
            //console.log("开始调用好友列表");
            conn.getRoster({
                success: function ( roster ) {
                    //获取好友列表，并进行好友列表渲染，roster格式为：
                    /** [
                     {
                       jid:"asemoemo#chatdemoui_test1@easemob.com",
                     name:"test1",
                     subscription: "both"
                     }
                     ]
                     */
                    //console.log("完成");
                    for ( var i = 0, l = roster.length; i < l; i++ ) {
                        var ros = roster[i];
                        //ros.subscription值为both/to为要显示的联系人，此处与APP需保持一致，才能保证两个客户端登录后的好友列表一致
                        if ( ros.subscription === 'both' || ros.subscription === 'to' ) {
                            //console.log(ros);
                        }
                    }
                },
                error:function(d){
                    console.log(d);
                }
            });
            //console.log("结束调用好友列表");
        },
        onClosed: function ( message ) {console.log("1");},         //连接关闭回调
        onEmojiMessage: function ( message ) {console.log("2");},   //收到表情消息
        onPictureMessage: function ( message ) {console.log("3");}, //收到图片消息
        onCmdMessage: function ( message ) {console.log("4");},     //收到命令消息
        onAudioMessage: function ( message ) {console.log("5");},   //收到音频消息
        onLocationMessage: function ( message ) {console.log("6");},//收到位置消息
        onFileMessage: function ( message ) {console.log("7");},    //收到文件消息
        onVideoMessage: function ( message ) {console.log("8");},   //收到视频消息
        onRoster: function ( message ) {console.log("10");},         //处理好友申请
        onInviteMessage: function ( message ) {console.log("11");},  //处理群组邀请
        onOnline: function () {console.log("12");},                  //本机网络连接成功
        onOffline: function () {console.log("13");},                 //本机网络掉线
        onError: function ( message ) {console.log("14");}           //失败回调
    });
}
$(document).ready(function(){
    if($.cookie("wxopenid")){
//==============================================================
        //从登录页返回有openid没有id
        if($.cookie("MYID")){
            allftn();
        }
        else{
            location.href="login.html";
        }
//==============================================================
    }
    else{
        //先微信验证获取openid 如果已经授权过了 直接页面截取openid 然后发送请求获取 用户的ID
        var reg=new RegExp("code=[a-zA-Z0-9]*");
        if(window.location.href.match(reg)){
            var code=window.location.href.match(reg);
            $.ajax({
                type:"GET",
                url:"GetOpenId.ashx?"+code,
                async: false,
                success:function(data){
                    var dat=$.parseJSON(data);
                    $.cookie("wxod",dat.openid);
                    //发请求获取用户的id
                    $.ajax({
                        type:"GET",
                        url:getwxopenidurl+dat.openid,
                        success:function(d){
                            //console.log("服务器openid获取的userID："+d);
                            //如果没有用户id 则证明用户是第一次登陆 保存openid跳转至登录页面
                            if(!d.Data){
                                $.cookie("wxopenid",dat.openid);
                                location.href="login.html";
                            }else if(d.Data&&d.Data.userId.length>0){

                                $.cookie("wxopenid",d.Data.webchatId);

                                $.cookie("MYID",d.Data.userId);
                                id=d.Data.userId;
//========================================================
                                allftn();
//========================================================
                            }
                            //如果有用户ID 就把cookies里的用户id替换成获取到的id  在这里控制跳转提示框
                        }
                    })
                }
            })
        }
        else{
            location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx658c34793ecfd9f9&redirect_uri="+returnurl+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        }
    }
})